<template>
  <div>
    <!-- 头部 -->
    <div class="search">
      <a-row style="align-items: center" :gutter="20">
        <span class="user-title">订单状态:</span>
        <a-col
          :span="2"
          :md="4"
          :lg="2"
          :xs="6"
          class="user-status"
          v-for="(item, index) in statusList"
          :class="item.id == form.status ? 'user-status-act' : ''"
          @click="chooseOrderStatus(item, index)"
          :key="index"
        >
          <div class="item-title">{{ item.name }}</div>
        </a-col>
      </a-row>
      <a-form ref="formRef" :model="form" :hideRequiredMark="true">
        <a-row :gutter="20">
          <a-col :span="5" :md="8" :lg="5" :xs="12">
            <a-form-item name="number" label="订单号">
              <a-input v-model:value="form.number" placeholder="请输入订单号" allow-clear></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="5" :md="8" :lg="5" :xs="12">
            <a-form-item name="name" label="申请人">
              <a-input v-model:value="form.name" placeholder="请输入申请人" allow-clear></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6" :lg="6" :xs="11" :md="8">
            <a-form-item label="申请时间">
              <a-range-picker
                v-model:value="time"
                style="width: 100%"
                :ranges="ranges"
                show-time
                format="YYYY/MM/DD HH:mm:ss"
                @change="panelChange"
              />
            </a-form-item>
          </a-col>

          <a-col :span="4"> <a-button type="primary" @click="search" class="d-a-center">搜索</a-button></a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 列表 -->

    <!-- 退款单 -->
    <a-table
      rowKey="id"
      :columns="columns"
      :data-source="list"
      bordered
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
      :scroll="{ y: 'auto', x: 'auto' }"
    >
      <template #status="{ record }">
        <a-tag :color="orderListStatusColor(record.status)">{{ orderListStatus(record.status) }}</a-tag>
      </template>
      <template #operation="{ record }">
        <a-button type="link" @click="look(record.number, record.status)" v-has="{ a: $route, b: 1 }">查看</a-button>
        <!-- v-if="record.status == 9" -->
        <a-button type="link" @click="deal(record.number, record.status)" v-has="{ a: $route, b: 2 }">审核</a-button>
      </template>
    </a-table>
    <!-- <a-button type="danger" @click="listDel">删除</a-button> -->

    <template v-if="visible">
      <order-refund-fresenius
        :visible="visible"
        :isEdit="isEdit"
        @closeModal="closeModal"
        :number="number"
        :status="status"
      ></order-refund-fresenius>
    </template>
  </div>
</template>
<script>
import { reactive, ref, watch, computed, defineComponent, createVNode, toRefs } from 'vue'
import { CheckOutlined, EditOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { Modal, message } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'
import OrderRefundFresenius from '@/views/order/components/OrderRefundFresenius'
import { number } from 'echarts'
import { deleteObjBlank } from '@/assets/js/common.js'
import { selectFreseniusRefundOrder, cancelOrderUpload, selectAllRefundOrderIds } from '../../../api/order/index.js'
import { useModal, useSelects } from '@/hooks'
export default {
  components: {
    CheckOutlined,
    EditOutlined,
    ExclamationCircleOutlined,
    OrderRefundFresenius
  },
  setup() {
    const formRef = ref('')
    const form = reactive({
      status: 0
    })
    const data = reactive({
      list: [],
      loading: true,
      visible: false,
      order: {},
      time: [],
      number: '',
      selectedRowKeys: [],
      oldPage: 1,
      oldSelectedRowKeys: []
    })
    const router = useRouter()
    const route = useRoute()

    const isEdit = ref(false) //编辑or查看

    // 分页器
    const page = reactive({
      current: 1,
      pageSize: 10,
      total: 0
    })

    // 状态列表
    const statusList = reactive([
      {
        name: '全部',
        id: 0
      },
      {
        name: '待审核',
        id: 9
      },
      {
        name: '已退款',
        id: 7
      },
      {
        name: '已拒绝',
        id: 10
      },
      {
        name: '已取消',
        id: 6
      }
    ])
    const orderListStatus = status => {
      let title = ''
      switch (status) {
        case 9:
          title = '待审核'
          break
        case 7:
          title = '已退款'
          break
        case 10:
          title = '已拒绝'
          break
        case 6:
          title = '已取消'
          break
      }
      return title
    }

    // 查询
    const search = () => {
      console.log(form, '表单内容')
      if (Object.keys(form).length == 0) {
        message.warning('请输入你要搜索的内容！！！')
        return
      }
      deleteObjBlank(form)
      page.current = 1
      rowSelection.selectedRowKeys = []
      init()
    }
    const excleData = () => {
      if (rowSelection.selectedRowKeys.length == 0) {
        message.warning('请选择你要导出的订单')
        return
      }
      let len = 0

      const { closeModal } = useModal.confirm({
        // ${data.list.length}
        title: `确认导出当前${rowSelection.selectedRowKeys.length}条数据吗?`,
        icon: createVNode(ExclamationCircleOutlined),
        onOk() {
          let obj = {
            ...form,
            orderIds: rowSelection.selectedRowKeys
          }
          cancelOrderUpload({
            ...obj
          }).then(res => {
            console.log(res)
            let link = document.createElement('a')
            //创建一个a标签
            link.style.display = 'none'
            //将a标签隐藏
            link.href = res.object
            //给a标签添加下载链接  "域名+接口"  safe是一个动态的域名  后面的接口替换成你自己的下载接口
            link.setAttribute('download', '订单')
            // 此处注意，要给a标签添加一个download属性，属性值就是文件名称 否则下载出来的文件是没有属性的，空白白
            document.body.appendChild(link)
            //将上面创建的a标签加入到body的尾部
            link.click()
            closeModal()
          })
        },

        class: 'test'
      })
    }

    // 选择时间
    const panelChange = (date, dateString) => {
      console.log('选择的时间是', dateString)
      form.startTime = dateString[0]
      form.endTime = dateString[1]
    }

    const columns = [
      {
        title: '订单号',
        dataIndex: 'number',
        className: 'table',
        align: 'center'
      },
      {
        title: '下单时间',
        dataIndex: 'orderCreatedAt',
        className: 'table',
        align: 'center'
      },
      {
        title: '渠道来源',
        dataIndex: 'institution',
        className: 'table',
        align: 'center'
      },
      {
        title: '申请时间',
        dataIndex: 'createdAt',
        className: 'table',
        align: 'center',
        sort: true
      },
      {
        title: '申请人',
        dataIndex: 'name',
        className: 'table',
        align: 'center'
      },
      {
        title: '退款方式',
        dataIndex: 'channel',
        className: 'table',
        align: 'center'
      },
      {
        title: '退款状态',
        dataIndex: 'status',
        className: 'table',
        align: 'center',
        slots: {
          customRender: 'status'
        }
      },
      {
        title: '实际退款金额',
        dataIndex: 'endPrice',
        className: 'table',
        align: 'center'
      },
      {
        title: '处理时间',
        dataIndex: 'updateAt',
        className: 'table',
        align: 'center'
      },
      {
        title: '操作',
        dataIndex: 'operation',
        className: 'table',
        align: 'center',
        fixed: 'right',
        slots: {
          customRender: 'operation'
        }
      }
    ]
    // 订单列表对应的状态
    const orderListStatusColor = computed(status => {
      return function (status) {
        if (status == 9) {
          return 'error'
        }
        if (status == 7) {
          return 'success'
        }
        if (status == 10) {
          return '#f50'
        }
        return '#f50'
      }
    })

    // 分页器
    const pagination = computed(() => ({
      current: page.current,
      pageSize: page.pageSize,
      pageSizeOptions: ['10', '20', '30'],
      showTotal: (total, range) => {
        return '共' + total + '条'
      },
      total: page.total,
      showQuickJumper: true,
      showSizeChanger: true,
      oldPage: page.current
    }))

    // 分页器改变的时候
    const handleTableChange = (pagination, filters, sorter) => {
      console.log(pagination, '当前分页')
      data.oldPage = pagination.oldPage
      page.current = pagination.current
      page.pageSize = pagination.pageSize

      // 请求列表接口
      init()
    }
    const hasSelected = computed(() => data.selectedRowKeys.length > 0)
    const { renderData, rowSelection } = useSelects({})
    // 全选反选

    // 删除多项
    const listDel = () => {
      const { closeModal } = useModal.confirm({
        title: '确定删除所选内容项吗?',
        icon: createVNode(ExclamationCircleOutlined),
        content: '删除后将不可恢复，请谨慎操作。',
        okText: '确定',
        okType: 'danger',
        cancelText: '取消'
      })
    }
    const closeModal = () => {
      data.visible = false
      // 更新下
      if (isEdit.value) {
        init()
      }
    }

    // 查看
    const look = (key, status) => {
      data.number = key
      console.log(key)

      isEdit.value = false
      data.visible = true
      data.status = orderListStatus(status)
    }

    // 处理
    const deal = (key, status) => {
      data.number = key

      isEdit.value = true
      data.visible = true
      data.status = orderListStatus(status)
    }
    const getSelectAllRefundOrderIds = obj => {
      selectAllRefundOrderIds(obj).then(res => {
        renderData.value = res.object
      })
    }
    init()
    async function init() {
      let obj = {
        pageNum: page.current,
        pageSize: page.pageSize,
        ...form
      }
      getSelectAllRefundOrderIds(obj)
      let res = await selectFreseniusRefundOrder(obj)
      if (res.success) {
        res.object.list.map(el => (el.key = el.number))
        data.list = res.object.list
        page.total = res.object.total
        // renderData.value = res.object.allOrderIds;
      }
      data.loading = false
    }
    // 选择订单状态查询
    const chooseOrderStatus = (item, index) => {
      form.status = item.id
      page.current = 1
      rowSelection.selectedRowKeys = []
      init()
    }
    return {
      ...toRefs(data),
      chooseOrderStatus,
      excleData,
      formRef,
      form,
      columns,
      pagination,
      statusList,
      handleTableChange,
      search,
      panelChange,
      deal,
      look,
      rowSelection,
      listDel,
      closeModal,
      isEdit,
      orderListStatus,
      orderListStatusColor,
      hasSelected
    }
  }
}
</script>
<style scoped lang="less">
.img {
  width: 50px;
  height: 50px;
}

.title {
  font-weight: bold;
}

.ant-row {
  margin-bottom: 20px;
  margin-left: 0px;
}
.search {
  background-color: #e6e6e6;
  margin-bottom: 20px;
  padding: 0 1.6rem;

  // font-size: 1rem;

  .user-title {
    // font-size: 1.5rem;
    // font-weight: bold;
  }

  .user-status {
    text-align: center;
    padding: 12px 0;
    font-size: 1.25rem;
  }

  .user-status-act {
    width: 70%;

    .item-title {
      background-color: #2a9d8f;
      color: #fff;
      border-radius: 20rem;
    }
  }
}
</style>
